
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";

export interface Sorter {
    columnKey?: string | null;
    order?: string | null;
}

export function useSorter(id: string) {

    const navigate = useNavigate();
    const location = useLocation();

    const sorterData = React.useMemo<Sorter>(() => {
        return location.state?.[id] || {} as Sorter;
    }, [id, location.state])

    const setSorterData = React.useCallback((data: Sorter) => {
        navigate({
            pathname: location.pathname,
            search: location.search
        }, {
            state: { ...location.state, [id]: data }
        });
    }, [id, location.pathname, location.search, location.state, navigate]);

    return {
        sorterData,
        setSorterData,
    }
}